<?php
namespace core;
//创建httpClinet的工具类
final class HttpUtil{
	static function getClient($cookiePath=null){
		return new HttpClient($cookiePath);
	}
}

//封装http抓取网页类，可自动管理Cookie
class HttpClient{
	private $cookieStr = '';
	function __construct($cookiePath=null,$isAuto=false){
		$this->cookiePath = $cookiePath;
		if(!empty($cookiePath)){
			if(file_exists($cookiePath))
				$this->cookieStr = file_get_contents($cookiePath);
		}
		$this->isAutoCookie = $isAuto;
	}
	
	function setCookieStr($cookieStr){
		$this->cookieStr = $cookieStr;
	}
	
	function setAutoCookie($isAuto = false){
		$this->isAutoCookie = $isAuto;
	}
	/**
	* 参数1：$url = 'http://xxxxxxxx'
	* 参数2：$configArr = ['encode'='utf-8','referIp'='192.168.0.5','referer'='http://xxx',userAgent='']
	*/
	function get($url,$configArr=[]){
		$default =[
			'encode'=>null,
			'referIp'=>null,
			'userAgent'=>null,
			'referer'=>null
		];
		\core\Util::copyProperties($default,$configArr);
		return $this->_request($url,false,null,$default['encode'],$default['referIp'],$default['referer']);
	}
	
	/**
	* 参数1：$url = 'http://xxxxxxxx'
	* 参数2：$params = 'a=1&b=2' 或 ['a'=>1,'b'=>2]
	* 参数2：$configArr = ['encode'='utf-8','referIp'='192.168.0.5','referer'='http://xxx',userAgent='']
	*/
	function post($url,$params=null,$configArr=[]){
		$default =[
			'encode'=>null,
			'referIp'=>null,
			'userAgent'=>null,
			'referer'=>null
		];
		\core\Util::copyProperties($default,$configArr);
		return $this->_request($url,true,$params,$default['encode'],$default['referIp'],$default['referer']);
	}
	
	private function _request($url,$isPost=false,$params=null,
						$encode=null,$refererIp=null,$referer=null,$userAgent=null){
		$ch  = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //返回数据不直接输出
		if(!empty($referer)){
			curl_setopt($ch, CURLOPT_REFERER, $referer);    //来路模拟
		}
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); //是否抓取跳转后的页面,1是自动跳转 
		curl_setopt($ch, CURLOPT_TIMEOUT,30);  //cURL允许执行的最长秒数
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10); //链接前最长等待时间
		 
		$encode||$encode='utf-8';
		$header = array(
			"content-type: application/x-www-form-urlencoded; charset=".$encode
		);
		if(!empty($refererIp)){
			$header[] = 'X-FORWARDED-FOR: ' . $refererIp;
			$header[] = 'CLIENT-IP: ' . $refererIp;
		}
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		if($isPost){
			curl_setopt($ch, CURLOPT_POST, 1);//发送POST类型数据
			if(!empty($params)){
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));  
			}
		}
		
		//模拟user-agent
		if(!empty($userAgent)){
			curl_setopt($ch,CURLOPT_USERAGENT,$userAgent);
		}
		
		//处理cookie,使用cookie路径进行自动管理cookie
		if(!empty($this->cookieStr)){
			curl_setopt($ch, CURLOPT_COOKIE, $this->cookieStr);
		}
		
		//自动处理Cookie
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($resURL, $strHeader){
			/*
			if(preg_match ('/Content-Type: ([^ ]+)/i' , $strHeader, $matches)){
				header("Content-Type: $matches[1]"); 
			}
			*/
			if($this->isAutoCookie){
				if(preg_match_all('/Set-Cookie:(.*);/iU',$strHeader,$results)){
					foreach($results[1] as $c){
						$arr = explode('=',$c);
						$name = trim($arr[0]);
						$value = trim($arr[1]);
						if(strpos($this->cookieStr,$name)){
							//先删除
							$this->cookieStr=preg_replace("/".$name."[^;]+/",'',$this->cookieStr);
						}
						if(\core\Util::endWith($this->cookieStr,';')) 
								$this->cookieStr .= $c;
						else $this->cookieStr .= ';'.$c;
					}
				}
			}
			return strlen($strHeader); 
		}); 
		
		$content = curl_exec($ch);
		curl_close($ch);
		return $content;
	}
	
	public function __destruct(){	
		if($this->isAutoCookie){
			if(!empty($this->cookiePath)&&!empty($this->cookieStr)){
				\core\FileUtil::save($this->cookiePath,$this->cookieStr);
			}
		}
    }
}